package ${package}.sys.dao;


import ${package}.sys.entity.Dictionary;
import cn.tannn.jdevelops.jpa.repository.JpaBasicsRepository;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 字典表
 *
 * @author tnnn
 * @version V1.0
 * @date 2024-10-9
 */
public interface DictionaryDao extends JpaBasicsRepository<Dictionary,Integer> {

    /**
     * 查询字典
     *
     * @param parentCode 父级code
     * @return Dictionary of List
     */
    List<Dictionary> findByParentCode(String parentCode);

    /**
     * 查询字典
     *
     * @param parentCode 父级code
     * @return Dictionary of List
     */
    List<Dictionary> findByParentCode(String parentCode, Sort sort);


    /**
     * 查询字典 [父级+name唯一]
     *
     * @param parentCode 父级code
     * @param name       name
     * @return Dictionary
     */
    Optional<Dictionary> findByParentCodeAndName(String parentCode, String name);

    /**
     * 查询字典
     *
     * @param parentCode 父级code
     * @param status     状态;0、不可用，1、可用
     * @return Dictionary of List
     */
    List<Dictionary> findByParentCodeAndAndStatus(String parentCode, Integer status);

    /**
     * 需改排序
     *
     * @param sort 新的排序
     * @param id   id
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("update Dictionary d set d.sort = :sort where  d.id = :id ")
    void fixSort(@Param("sort") Integer sort, @Param("id") Integer id);

    /**
     * 查询有效的字典
     *
     * @return Dictionary
     */
    @Query("select d from Dictionary d where d.status = 1 order by d.sort asc ")
    List<Dictionary> findEfficacious();

    /**
     * 查询有效的字典
     *
     * @param parentCode 父级code
     * @return Dictionary
     */
    @Query("select d from Dictionary d where d.status = 1 and d.parentCode = :parentCode  order by d.sort asc ")
    List<Dictionary> findEfficacious(String parentCode);

    /**
     * 根据父级code查询所有子级 [前缀匹配父级code,获取所有子级]
     *
     * @param code 父级code
     * @return Dictionary
     */
    @Query("select d from Dictionary d where d.parentCode like %?1 ")
    List<Dictionary> findLowLevel(String code);


    /**
     * 获取字典
     *
     * @param code code
     * @return Dictionary
     */
    Optional<Dictionary> findByCode(String code);
}
